package ti.me.seek2chat.activities

import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Base64
import android.util.Log
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.Toast
import cn.leancloud.LCUser
import ti.me.seek2chat.adapters.RecentConversationsAdapter
import ti.me.seek2chat.databinding.ActivityMainBinding
import ti.me.seek2chat.leancloud.LeanCloudService
import ti.me.seek2chat.listeners.ConversionListener
import ti.me.seek2chat.models.ChatMessage
import ti.me.seek2chat.models.User
import ti.me.seek2chat.utilities.Constants
import ti.me.seek2chat.utilities.PreferenceManager

/**
 * MainActivity 是应用的主活动类。
 *
 * 这个类负责显示用户的主要界面，并处理用户的登出、令牌更新等操作。
 */
class MainActivity : BaseActivity(), ConversionListener {
    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private lateinit var preferenceManager: PreferenceManager
    private lateinit var leanCloudService: LeanCloudService
    private lateinit var conversations: ArrayList<ChatMessage>
    private lateinit var conversationsAdapter: RecentConversationsAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        preferenceManager = PreferenceManager(applicationContext)
        init()
        updateToken()
        setListeners()
        loadUserDetails()
        listenConversations()
    }

    private fun init() {
        conversations = ArrayList()
        conversationsAdapter = RecentConversationsAdapter(conversations, this)
        binding.conversationsRecyclerView.adapter = conversationsAdapter
        leanCloudService = LeanCloudService(applicationContext)
    }

    /**
     * 绑定事件
     */
    private fun setListeners() {
        binding.imageSignOut.setOnClickListener { signOut() }
        binding.fabNewChat.setOnClickListener {
            val intent = Intent(applicationContext, UsersActivity::class.java)
            startActivity(intent)
        }
    }

    /**
     * 加载用户详细信息
     */
    private fun loadUserDetails() {
        binding.textName.text = preferenceManager.getString(Constants.KEY_NAME)
        val imageString = preferenceManager.getString(Constants.KEY_IMAGE)
        if (imageString != null) {
            val bytes = Base64.decode(imageString, Base64.DEFAULT)
            val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
            binding.imageProfile.setImageBitmap(bitmap)
        }
    }

    /**
     * 用户登出操作
     */
    private fun signOut() {
        showToast("Signing out...")
        LCUser.logOut()
        preferenceManager.clear()
        val intent = Intent(applicationContext, SignInActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        startActivity(intent)
    }

    /**
     * 更新用户sessionToken
     */
    private fun updateToken() {
        val currentUser = LCUser.getCurrentUser()
        if (currentUser != null) {
            val token = LCUser.getCurrentUser().sessionToken
            val deviceToken = preferenceManager.getString(Constants.KEY_SESSION_TOKEN)
            Log.d("MainActivity updateToken", "Device Token: $deviceToken, Token: $token")
            if (!token.equals(deviceToken)) {
                preferenceManager.putString(Constants.KEY_SESSION_TOKEN, token)
            }
        } else {
            showToast("Session expired, please sign in again")
            signOut()
        }
    }

    private fun listenConversations() {
        val userId = preferenceManager.getString(Constants.KEY_USER_ID) ?: ""
        leanCloudService.listenForConversations(userId) { success, messages, errorMessage ->
            if (success && messages != null) {
                val uniqueConversations = mutableMapOf<String, ChatMessage>()
                for (message in messages) {
                    val key =
                        if (message.senderId == userId) message.receiverId else message.senderId
                    val existingMessage = uniqueConversations[key]
                    if (existingMessage == null || message.dateTime > existingMessage.dateTime) {
                        uniqueConversations[key] = message
                    }
                }
                conversations.clear()
                conversations.addAll(uniqueConversations.values)
                conversations.sortByDescending { it.dateTime }
                conversationsAdapter.notifyDataSetChanged()
                binding.conversationsRecyclerView.smoothScrollToPosition(0)
                binding.conversationsRecyclerView.visibility = VISIBLE
                binding.progressBar.visibility = GONE
            } else {
                showToast(errorMessage ?: "Failed to load conversations")
                binding.progressBar.visibility = GONE
            }
        }
    }

    /**
     * 显示 Toast 消息
     *
     * @param message 消息内容
     */
    private fun showToast(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    override fun onConversionClicked(user: User) {
        val intent = Intent(applicationContext, ChatActivity::class.java)
        intent.putExtra(Constants.KEY_USER, user)
        startActivity(intent)
    }
}

